<?PHP
require_once("functions.php");
require_once("update.php");
require_once("QuickPicks.php");
include("TeamHashes.php");
//-----------------------------------------------------------------
function setGameWinner($homeTeam, $homeScore, $awayTeam, $awayScore, $Week, $League)
{
	echo "In setGameWinner($homeTeam, $homeScore, $awayTeam, $awayScore, $Week, $League) </br>";
	switch ($League)
	{
	case "NFL"://National Football League
		{	
		global $NFLTeamNames;
		$TeamNames = $NFLTeamNames;
		}
		break;
	case "AFL"://Arena Football League
		{	
		global $AFLTeamNames;
		$TeamNames = $AFLTeamNames;
		}
		break;
	}
	
	//Check to see if game is over and has been updated in DB
	if(!IsGameOver($TeamNames[$homeTeam], $TeamNames[$awayTeam], $Week, $League))
	{
		if (decideWinLoss($homeScore, $awayScore) == "win") //if home team wins
			setWinner($TeamNames[$homeTeam], $TeamNames[$homeTeam], $TeamNames[$awayTeam], $League);	//set Home team as winner
		else
			setWinner($TeamNames[$awayTeam], $TeamNames[$homeTeam], $TeamNames[$awayTeam], $League);	//set away team as winner
		//Update win/loss stats for both teams
		updateTeamStats($TeamNames[$homeTeam], $homeScore, $TeamNames[$awayTeam], $awayScore, $League);
		//If this is the last game of the week, the total score is the Magic Number for the week, set it.
		if(lastGame($Week,$TeamNames[$homeTeam], $TeamNames[$awayTeam], $League))
		{
			echo "last game of the week is between the $TeamNames[$homeTeam] and $TeamNames[$awayTeam]<br/>";
			setMagicNumber($Week,$homeScore,$awayScore, $League);
			setWeeklyWinner($Week, $League);
		}
		/**/
	}
	else
	{
		echo "\nGame between $TeamNames[$homeTeam] and $TeamNames[$awayTeam] is over and updated<br/>";
	}
	
}
//-----------------------------------------------------------------
function IsGameOver($home, $away, $currWeek, $League)
{
	//$currWeek = getWeek($League);
	$SQL = "SELECT GameNum FROM ".$League."Schedule Where (Winner != '-' AND Home='$home' AND Away='$away' AND Week = $currWeek)";
	mysql_query($SQL) or die("Cannot query the database.<br/>");
	if(mysql_affected_rows() > 0)
		return true;
	else 
		return false;
}
//-----------------------------------------------------------------
function decideWinLoss($hScore, $aScore)
{
	if ($hScore > $aScore) {
		return "win";
	} else if ($aScore > $hScore) {
		return "loss";
	} else {
		return "tie";
	}
}
//-----------------------------------------------------------------
function setWinner($winner, $home, $away, $League)
{
	$SQL = "UPDATE ".$League."Schedule Set Winner='$winner',PickEMailed=1 Where (Home='$home' AND Away='$away')";
	mysql_query($SQL) or die("Cannot query the database.<br/>");
	echo " Setting $winner as a winner...<br/>";
}
//-----------------------------------------------------------------
function lastGame($Week,$homeTeam,$awayTeam,$League)
{	
	//Get This Game number
	$result = mysql_query("SELECT GameNum FROM ".$League."Schedule WHERE (Week=$Week AND Home='$homeTeam' AND Away='$awayTeam')") or die("Cannot query the database.<br/>");
	if($myrow = mysql_fetch_array($result))
		if(($myrow["GameNum"] != NULL) && ($myrow["GameNum"] != ""))
			$ThisGameNum = $myrow["GameNum"];
	//Get Last Game number this week
	$result = mysql_query("SELECT MAX(GameNum) FROM ".$League."Schedule WHERE Week=$Week") or die("Cannot query the database.<br/>");
	if($myrow = mysql_fetch_array($result))
		if(($myrow["MAX(GameNum)"] != NULL) && ($myrow["MAX(GameNum)"] != ""))
			$lastGameNum = $myrow["MAX(GameNum)"];
	//Compare ThisGameNum & lastgameNum
	if ($ThisGameNum == $lastGameNum)
		return true;
	else
		return false;
}
//-----------------------------------------------------------------
function setMagicNumber($Week,$homeScore,$awayScore,$League)
{	
	$SQL = "INSERT INTO ".$League."WeeklyWinner (Week, MagicNum, NumGames) VALUES ($Week,".($homeScore + $awayScore).",".getGameCount($Week,$League).")";
	mysql_query($SQL) or die("Cannot query the database.<br/>");
}
//------------------------------------------------------------------------------
function checkPickEmailer($homeTeam, $awayTeam,$League)
{
	switch ($League)
	{
	case "NFL"://National Football League
		{	
		global $NFLTeamNames;
		$TeamNames = $NFLTeamNames;
		}
		break;
	case "AFL"://Arena Football League
		{	
		global $AFLTeamNames;
		$TeamNames = $AFLTeamNames;
		}
		break;
	}
	$SQL = "SELECT GameDate, GameTime, PickEmailed FROM ".$League."Schedule Where (Week = ".getWeek($League)." AND Home='".$TeamNames[$homeTeam]."' AND Away='".$TeamNames[$awayTeam]."')";
	$result = mysql_query($SQL) or die("Cannot query the database.<br/>");
	$GameDateStr = date("Ymd");
	if($myrow = mysql_fetch_array($result))
	{
		if($myrow["PickEmailed"] == 1)
		{
			//do Nothing, the picks have already been sent out once
		}
		else
		{
			//makeSysQuickPicks(getWeek($League));	//Make Picks for users who still have null picks
			//emailPicks(str_replace(":", "",$myrow["GameTime"]));
			mysql_query("UPDATE ".$League."Schedule SET PickEMailed = 1 WHERE (Week = ".getWeek($League)." AND GameDate='".$GameDateStr."' AND GameTime='".$myrow["GameTime"]."')") or die("Cannot query the database.<br/>");
		}
	}
	else
	{
		echo " Some Problem with pick emailer...<br/>";
	}

}
//-----------------------------------------------------------------
function updateTeamStats($homeTeam, $homeScore, $awayTeam, $awayScore, $League)
{
	// Pull HomeTeam Information out of the DB
	$HomeSQL = "SELECT * FROM ".$League."Teams WHERE TeamName='$homeTeam'";
	//Open Record Set using SQL Query
	$HomeResult = mysql_query($HomeSQL) or die("Cannot query the database.<br/>");
	$HomeRow = mysql_fetch_array($HomeResult);
	
	// Pull HomeTeam Information out of the DB
	$AwaySQL = "SELECT * FROM ".$League."Teams WHERE TeamName='$awayTeam'";
	//Open Record Set using SQL Query
	$AwayResult = mysql_query($AwaySQL) or die("Cannot query the database.<br/>");
	$AwayRow = mysql_fetch_array($AwayResult);
	
	##################################################################################
	// Create new SQL statement to update HOME team
		$SQL = "UPDATE ".$League."Teams SET ";
		$SQL.= "PointsFor = ".($HomeRow["PointsFor"] + $homeScore).", ";
		$SQL.= "PointsAgainst = ".($HomeRow["PointsAgainst"] + $awayScore).", ";
		#list($winloss, $streakNum) = explode(" ", $HomeRow["Streak"]);
		$Homewinloss = substr($HomeRow["Streak"], 0, 1);
		$HomestreakNum = substr($HomeRow["Streak"], 2);
		if (decideWinLoss($homeScore, $awayScore) == "win") //if home team wins
		{	//*************************** Home team Wins ***************************
			### Update HOME team overall win/loss record ###
			$SQL.= "Wins = ".($HomeRow["Wins"] + 1).", HomeWins = ".($HomeRow["HomeWins"] + 1).", ";
			
			### Update HOME team conference win/loss record ###
			if($AwayRow["Conference"] == "AFC")  //Opponent is in AFC
				$SQL.= "AFCWins = ".($HomeRow["AFCWins"] + 1).", ";
			else 								//Opponent is in NFC
				$SQL.= "NFCWins = ".($HomeRow["NFCWins"] + 1).", ";
			
			### Update HOME team division win/loss record (if neccessary) ###
			if (($HomeRow["Conference"] == $AwayRow["Conference"]) && ($HomeRow["Division"] == $AwayRow["Division"])) //Opponent is in teams own division
				$SQL.= "DivWins = ".($HomeRow["DivWins"] + 1).", ";			
			
			### Update HOME team streak ###
			if($Homewinloss == "W")
			{
				$HomestreakNum++;
			}
			else
			{
				$Homewinloss = "W";
				$HomestreakNum = 1;
			}
		}
		else	//*************************** Home team looses ***************************
		{
			### Update HOME team overall win/loss record ###
			$SQL.= "Loses = ".($HomeRow["Loses"] + 1).", HomeLosses = ".($HomeRow["HomeLosses"] + 1).", ";
			
			### Update HOME team conference win/loss record ###
			if($AwayRow["Conference"] == "AFC")	//Opponent is in AFC
				$SQL.= "AFCLosses = ".($HomeRow["AFCLosses"] + 1).", ";
			else								//Opponent is in NFC
				$SQL.= "NFCLosses = ".($HomeRow["NFCLosses"] + 1).", ";
			
			### Update HOME team division win/loss record (if neccessary) ###
			if (($HomeRow["Conference"] == $AwayRow["Conference"]) && ($HomeRow["Division"] == $AwayRow["Division"]))
			{	//Opponent is in teams own division
				$SQL.= "DivLosses = ".($HomeRow["DivLosses"] + 1).", ";			
			}
			
			### Update HOME team streak ###			
			if($Homewinloss == "L")
			{
				$HomestreakNum++;
			}
			else
			{
				$Homewinloss = "L";
				$HomestreakNum = 1;
			}
		}
		$SQL.= " Streak = '".$Homewinloss." ".$HomestreakNum."'";
		$SQL.= " WHERE TeamName='$homeTeam'";
		// Execute Home Team Update Query
		mysql_query($SQL) or die("Cannot query the database.<br/>");
		#echo $SQL."<br/>";
		
	##################################################################################
	// Create new SQL statement to update AWAY team
		$SQL = "UPDATE ".$League."Teams SET ";
		$SQL.= "PointsFor = ".($AwayRow["PointsFor"] + $awayScore).", ";
		$SQL.= "PointsAgainst = ".($AwayRow["PointsAgainst"] + $homeScore).", ";
		#list($winloss, $streakNum) = explode(" ", $AwayRow["Streak"]);
		$Awaywinloss = substr($AwayRow["Streak"], 0, 1);
		$AwaystreakNum = substr($AwayRow["Streak"], 2);
		if (decideWinLoss($awayScore, $homeScore) == "win") //if AWAY team wins
		{
			### Update AWAY team overall win/loss record ###
			$SQL.= "Wins = ".($AwayRow["Wins"] + 1).", RoadWins = ".($AwayRow["RoadWins"] + 1).", ";
			
			### Update AWAY team conference win/loss record ###
			if($HomeRow["Conference"] == "AFC") //Opponent is in AFC
				$SQL.= "AFCWins = ".($AwayRow["AFCWins"] + 1).", ";
			else 								//Opponent is in NFC
				$SQL.= "NFCWins = ".($AwayRow["NFCWins"] + 1).", ";
			
			### Update AWAY team division win/loss record (if neccessary) ###
			if (($HomeRow["Conference"] == $AwayRow["Conference"]) && ($HomeRow["Division"] == $AwayRow["Division"]))
				$SQL.= "DivWins = ".($AwayRow["DivWins"] + 1).", ";		//Opponent is in teams own division		
			
			### Update AWAY team streak ###
			if($Awaywinloss == "W")
			{
				$AwaystreakNum++;
			}
			else
			{
				$Awaywinloss = "W";
				$AwaystreakNum = 1;
			}
		}
		else	 	//*************************** AWAY team looses ***************************
		{
			### Update AWAY team overall win/loss record ###
			$SQL.= "Loses = ".($AwayRow["Loses"] + 1).", RoadLosses = ".($AwayRow["RoadLosses"] + 1).", ";
			
			### Update AWAY team conference win/loss record ###
			if($HomeRow["Conference"] == "AFC") //Opponent is in AFC
				$SQL.= "AFCLosses = ".($AwayRow["AFCLosses"] + 1).", ";
			else 								//Opponent is in NFC
				$SQL.= "NFCLosses = ".($AwayRow["NFCLosses"] + 1).", ";
			
			### Update AWAY team division win/loss record (if neccessary) ###
			if (($HomeRow["Conference"] == $AwayRow["Conference"]) && ($HomeRow["Division"] == $AwayRow["Division"]))
				$SQL.= "DivLosses = ".($AwayRow["DivLosses"] + 1).", ";		//Opponent is in teams own division	
			
			### Update AWAY team streak ###
			if($Awaywinloss == "L")
			{
				$AwaystreakNum++;
			}
			else
			{
				$Awaywinloss = "L";
				$AwaystreakNum = 1;
			}
		}
		$SQL.= " Streak = '".$Awaywinloss." ".$AwaystreakNum."'";
		$SQL.= " WHERE TeamName='$awayTeam'";
		// Execute Home Team Update Query
		mysql_query($SQL) or die("Cannot query the database.<br/>");
		#echo $SQL."<br/>";
}
//-------------------------------------------------------------------------------------------------
function emailPicks($GameTime,$League)
{
	$Weeknum = getWeek($League);
	
	//check to make sure $Weeknum > 1 AND $Weeknum < 21
	$Weeknum = checkWeekBounds($Weeknum);
	
	//Select user information from the Users table, if the user wants to be reminded
	if($Weeknum > 17)
		$SQL = "SELECT ID, username, email FROM ".$League."Users WHERE PlayOffs = 1 AND EmailPicks = 1 ORDER BY username";
	else
		$SQL = "SELECT ID, username, email FROM ".$League."Users WHERE EmailPicks = 1";

	$GameTimeStr = date("g:i",mktime(substr($GameTime, 0, 2), substr($GameTime, 2, 2), substr($GameTime, 4, 2), date("m") , date("d"), date("Y")));
	$GameDateStr = date("Ymd");
	//Open Record Set using SQL Query
	$Emailresult = mysql_query($SQL) or die("Cannot query the database.<br/>");
	//set up some email varibables
	$adminmail = "<Football@joshhughes.com>";
	$MailFrom = "From: Football@joshhughes.com";
	$MailSubject = "$League Football Picks For Today's $GameTimeStr Game(s)";
	$MailBody = "Here are the users picks for today's $GameTimeStr game(s)";
	$HTMLMailBody = "Here are the users picks for today's $GameTimeStr game(s):<br/>(NP = \"No Pick Made\")<br/><br/>";
	do{
		if ($Emailrow["email"] != "") {   //add user's email to the list.
		$adminmail .= ", ".$Emailrow["username"]." <".$Emailrow["email"].">";
		}//end if ($Emailrow["email"] != "")
	}while($Emailrow = mysql_fetch_array($Emailresult));

	$HTMLMailBody .=  "<table bgcolor=\"#FFFFFF\" border=\"1\" callpadding=\"5\" cellspacing=\"0\" width=\"100\" align=\"left\">";
	$query="SELECT * FROM ".$League."Schedule Where ((WEEK=".$Weeknum.") AND (GameDate = ".$GameDateStr.") AND (GameTime = ".$GameTime.")) GROUP BY GameNum";
	$doQuery=mysql_query($query);
	$numrows=mysql_num_rows($doQuery);
	$num = 1;
	if($numrows > 0)
	{
		while($results=mysql_fetch_array($doQuery))
		{
			//Fill Arrays With Data
			$homeTeams[$num]=$results['Home'];
			$awayTeams[$num]=$results['Away'];
			$gamenums[$num]=$results['GameNum'];
			$num++;		
		}
		//Print Away Line
		$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\"><td><b>Away</b></td>";
		foreach($awayTeams as $team)
		{
		  $HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$team.".gif\"></td>";
		}
		
		//Print @ Line
		$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\"><td>&nbsp;</td>";
		foreach($homeTeams as $team)
		{
		  $HTMLMailBody .=  "<td width=\"5\" align=\"center\">@</td>";
		}
		$HTMLMailBody .=  "</tr>";
		
		//Print Home Line
		$HTMLMailBody .=  "<tr bgcolor=\"#FFFFFF\" bordercolor=\"#172693\"><td><b>Home</b></td>";
		foreach($homeTeams as $team)
		{
		  $HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$team.".gif\"></td>";
		}
		$HTMLMailBody .=  "</tr>";
		
		$cols = $numrows + 2;
		$HTMLMailBody .=  "<tr height=\"1\" bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" bgcolor=\"#FF0000\"><span style=\"font-size: 8px;\"&nbsp;</td></tr>";
		
		//Get Data From Users Who Picked
		$UserPickedSQL = "SELECT ".$League."Picks.*, ".$League."Users.username, ".$League."Users.ID FROM ".$League."Picks, ".$League."Users WHERE ((".$League."Picks.Week = ".$Weeknum.") AND (".$League."Picks.UserID = ".$League."Users.ID))  ORDER BY ".$League."Picks.UserID ASC";
		$UserPickedresult = mysql_query($UserPickedSQL) or die("Cannot query the database.<br/>");
		$row = 0;
		do{
		
			if ($myrow["UserID"] != NULL)
			{
				//increment row for the row color
				$row++;
				$HTMLMailBody .=  "<tr bgcolor=\"".getrowColor($row)."\">";
				$HTMLMailBody .=  "<td><a href=\"members.php?ID=".$myrow["UserID"]."\" class=\"permLink\">".$myrow["username"]."</a></td>\n";
				$MailBody .= "\n\n".$myrow["username"]." Picked: \n";
				$weekScore = 0;
				for($j = 1; $j <= $numrows; $j++)
				{
					$pick = $myrow["Game".$gamenums[$j]];
					if($pick!="")
					{
						$HTMLMailBody .=  "<td width=\"5\" align=\"center\"><img src=\"http://football.joshhughes.com/images/small/".$pick.".gif\" /></td>\n";	
						$MailBody .= "\t".$pick."\n";			
					}
					else
					{
						$HTMLMailBody .=  "<td width=\"5\" align=\"center\">NP</td>\n";		
					}
				}
			}
			
		}while($myrow = mysql_fetch_array($UserPickedresult));
		
	}
	else
	{
		print '<tr bgcolor=\"#FFFFFF\"><td colspan=\"$cols\" align=\"center\">No Games Set for This Week Yet.</td></tr>';
	}
	//Close table
	$HTMLMailBody .=  "</table>";
	$HTMLMailBody .= "<BR><BR><BR><font size=1> Users may &quot;Opt Out&quot; of this feature by changing their preferences using the \"Change Email Prefs\" link in the Log On Box....<BR>This feature is turned on by default at user registration.</font>";
	$MailBody .= "\n\n\n Users may \"Opt Out\" of this feature by changing their preferences using the \"Change Email Prefs\" link in the Log On Box....\nThis feature is turned on by default at user registration.";

	$MailTo = $adminmail;
	//add From: header
	$headers = "From: Football@joshhughes.com\r\n";
	
	//specify MIME version 1.0
	$headers .= "MIME-Version: 1.0\r\n";
	
	//unique boundary
	$boundary = uniqid("HTMLDEMO");
	
	//tell e-mail client this e-mail contains//alternate versions
	$headers .= "Content-Type: multipart/alternative" ."; boundary = $boundary\r\n\r\n";
	
	//message to people with clients who don't
	//understand MIME
	$headers .= "This is a MIME encoded message.\r\n\r\n";
	
	//plain text version of message
	$headers .= "--$boundary\r\n" .
	 "Content-Type: text/plain; charset=ISO-8859-1\r\n" .
	 "Content-Transfer-Encoding: base64\r\n\r\n";
	$headers .= chunk_split(base64_encode($MailBody));
	
	//HTML version of message
	$headers .= "--$boundary\r\n" .
	 "Content-Type: text/html; charset=ISO-8859-1\r\n" .
	 "Content-Transfer-Encoding: base64\r\n\r\n";
	$headers .= chunk_split(base64_encode($HTMLMailBody));
	//Send an Email to me notifying me of a request
	#mail($MailTo, $MailSubject, "", $headers);  //message send
	mail($MailTo, $MailSubject, $MailBody, $MailFrom);  //message send
	
	echo "<H3>Picks Mailed to: $MailTo</H3>";
	echo $HTMLMailBody;
}
?>
